var express = require("express");
var User = require("./models/user");
var Scenery = require("./models/scenery");
var md5 = require("blueimp-md5");
var formidable = require("formidable");
var config = require("./routes/config");
var path = require("path");
var router = express.Router();
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var fs = require("fs");

const transporter = nodemailer.createTransport(
  smtpTransport({
    host: "smtp.qq.com", //代理商，这里写的qq的
    secure: true,
    port: 465,
    auth: {
      user: "869290983@qq.com", //授权邮箱
      pass: "risuavvkpzrebcbi" //// 这里密码不是qq密码，是你设置的smtp授权码
    }
  })
);
//处理上传图片
router.post("/upload", function (req, res) {
  // console.log(".....");
  const form = new formidable.IncomingForm();
  form.uploadDir = config.uploadDir;
  form.keepExtensions = true; //保留后缀
  form.parse(req, function (err, fields, files) {
    if (err) return res.json({
      status: 500
    })
    fs.rename(files.file.path, config.uploadDir + '\\' + files.file.name, err => {
      if (err)
        console.log(err)

    })
    res.json({
      tmp_path: files.file.name,
      url: 'http://localhost:5000/public/upload/' + files.file.name,
      status: 201
    });
  })

});
//获取景区列表
router.get("/scenerys", function (req, res) {
  const body = req.query;
  const size = parseInt(body.pagesize);
  const num = (parseInt(body.pagenum) - 1) * size;
  console.log(body);
  // var total = 0;
  Scenery.findAll().then(scenery => {
      res.json({
        status: 201,
        scenery: scenery
      });
    })
    .catch(err =>
      res.json({
        status: 500,
        msg: "查询失败",
        err: err.message
      })
    );
})
//删除景区信息
router.delete("/scenery", function (req, res) {
  const body = req.body;
  Scenery.destroy({
    where: {
      id: body.id
    }
  }).then(() => {
    res.json({
      status: 201
    });
  });
})
//获取用户列表
router.get("/users", function (req, res) {
  const body = req.query;
  const size = parseInt(body.pagesize);
  const num = (parseInt(body.pagenum) - 1) * size;
  // console.log(body);
  var total = 0;
  User.find({
      $and: [{
          name: {
            $regex: body.name
          }
        },
        {
          gender: {
            $regex: body.gender
          }
        },
        {
          rank: {
            $regex: body.rank
          }
        }
      ]
    })
    .count()
    .then(num => {
      total = num;
    });
  User.find({
      $and: [{
          name: {
            $regex: body.name
          }
        },
        {
          gender: {
            $regex: body.gender
          }
        },
        {
          rank: {
            $regex: body.rank
          }
        }
      ]
    })
    .skip(num)
    .limit(size)
    .then(user => {
      res.json({
        status: 201,
        user: user,
        total: total
      });
    })
    .catch(err =>
      res.json({
        status: 500,
        msg: "查询失败",
        err: err.message
      })
    );
});
//根据id查询信息
router.get("/user", function (req, res) {
  const body = req.query;
  console.log(body[0]);
  User.find({
    _id: body[0]
  }).then(user => {
    res.json({
      status: 201,
      user: user
    });
  });
});
//根据id删除
router.delete("/user", function (req, res) {
  const body = req.body;
  // console.log(body.id);
  User.remove({
    _id: body.id
  }).then(() => {
    res.json({
      status: 201
    });
  });
});
//根据id修改信息
router.put("/user", function (req, res) {
  const body = req.body;
  console.log(body);
  User.updateOne({
    _id: body._id
  }, {
    name: body.name,
    rank: body.rank,
    password: md5(body.password),
    gender: body.gender,
    changeTime: body.changeTime
  }).then(() => {
    res.json({
      status: 201
    });
  });
});
//验证用户名密码
router.post("/login", function (req, res) {
  // 1. 获取表单数据
  // 2. 查询数据库用户名密码是否正确
  // 3. 发送响应数据
  var body = req.body;
  User.findOne({
      name: body.name,
      password: md5(body.password)
    })
    .select("name password")
    .then(user => {
      if (!user)
        return res.json({
          status: 500,
          msg: "登录失败"
        });
      res.json({
        status: 200,
        user: user
      });
    })
    .catch(err => {
      console.log(err.message);
    });
});
//增加用户
router.post("/addUser", function (req, res) {
  const body = req.body;
  User.create({
      name: body.name,
      password: md5(body.password),
      gender: body.gender,
      rank: body.rank
    })
    .then(user => {
      res.json({
        status: 201,
        user: user
      });
    })
    .catch(err =>
      res.json({
        status: 500,
        msg: "添加失败"
      })
    );
});
//根据邮箱发送验证码
router.get("/register", function (req, res) {
  const body = req.query;
  // console.log(body[0]);
  var code = "";
  while (code.length < 5) {
    code += Math.floor(Math.random() * 10);
  }
  console.log(code);
  var mailOption = {
    from: "869290983@qq.com",
    to: body[0], //收件人
    subject: "上虞旅游信息管理平台注册校验码", //纯文本
    html: "<h1>欢迎注册本平台，您本次的注册验证码为：" + code + "</h1>"
  };

  transporter.sendMail(mailOption, function (error, info) {
    if (error) {
      res.json({
        status: 201
      });
      return console.info(error);
    } else {
      res.json({
        status: 200,
        code: code
      });
      // console.info("Message send" + code);5
    }
    transporter.close(); // 如果没用，关闭连接池
  });
});
//验证信息注册用户
router.post("/register", function (req, res) {
  // 1. 获取表单提交的数据
  //    req.body
  // 2. 操作数据库
  //    判断改用户是否存在
  //    如果已存在，不允许注册
  //    如果不存在，注册新建用户
  // 3. 发送响应
  var body = req.body;
  console.log(body);
  User.findOne({
      name: body.name
    })
    .then(user => {
      if (user)
        return res.json({
          status: 500,
          msg: "用户已存在"
        });
      User.create({
          name: body.name,
          password: md5(body.pass)
        })
        .then(user => {
          res.json({
            status: 200
          });
        })
        .catch(err =>
          res.json({
            status: 500,
            msg: err.message
          })
        );
    })
    .catch(err => {
      console.log(err.message);
    });
});

router.post("/profiles", function (req, res, next) {
  // console.log(req.session.user.email);
  const form = new formidable.IncomingForm();
  form.uploadDir = config.uploadDir;
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return next(err);
    }
    const body = fields;
    body.email = req.session.user.email;
    body.avatar = path.basename(files.avatar.path);
    User.update({
        email: body.email
      }, {
        avatar: body.avatar,
        bio: body.bio,
        birthday: body.birthday,
        gender: body.gender
      },
      function (err, ret) {
        if (err) {
          console.log(err);
        } else {
          console.log(ret);
        }
      }
    );
    req.session.user = body;
    alert("修改信息成功");
    res.render("settings/profile.html", {
      user: req.session.user,
      profile: "profile"
    });
  });
});

router.get("/logout", function (req, res) {
  // 清除登陆状态
  req.session.user = null;

  // 重定向到登录页
  res.redirect("/login");
});

router.get("/topics/new", function (req, res) {
  res.render("topic/new.html", {
    user: req.session.user
  });
});

router.post("/new", function (req, res) {
  res.render("index.html", {
    comment: req.body,
    user: req.session.user
  });
});

router.get("/settings/profile", function (req, res) {
  res.render("settings/profile.html", {
    user: req.session.user,
    profile: "profile"
  });
});

router.get("/settings/admin", function (req, res) {
  res.render("settings/admin.html", {
    user: req.session.user
  });
});

router.post("/settings/admin", function (req, res) {
  var body = req.body;
  console.log(body);
  User.findOne({
      email: req.session.user.email,
      password: md5(md5(body.Password1))
    },
    function (err, user) {
      if (err) {
        return res.status(500).json({
          err_code: 500,
          message: err.message
        });
      }

      // 如果邮箱和密码匹配，则 user 是查询到的用户对象，否则就是 null
      if (!user) {
        return res.status(200).json({
          err_code: 1,
          message: "password is invalid."
        });
      }

      if (body.Password2 === body.Password3) {
        User.update({
            email: req.session.user.email
          }, {
            password: md5(md5(body.Password2))
          },
          function (err, ret) {
            if (err) {
              return res.status(500).json({
                err_code: 500,
                message: err.message
              });
            }
          }
        );
        req.session.user = null;

        // 重定向到登录页
        res.render("login.html");
      }
    }
  );
});

router.use((err, req, res, next) => {
  //接受 next（err）
  // const err_log = `
  //   错误名：${err.name}
  //   错误消息：${err.message}
  //   错误堆栈：${err.stack}
  //   错误时间：${new Date()}`;
  // fs.appendFile("./err_log.txt", err_log, err => {
  //   res.writeHead(500, {});
  //   res.end("500, 服务器繁忙，请稍后重试");
  // });
  res.writeHead(500, {});
  res.end("500, 服务器繁忙，请稍后重试");
});

// router.post('/register', async function (req, res) {
//   var body = req.body
//   try {
//     if (await User.findOne({ email: body.email })) {
//       return res.status(200).json({
//         err_code: 1,
//         message: '邮箱已存在'
//       })
//     }

//     if (await User.findOne({ nickname: body.nickname })) {
//       return res.status(200).json({
//         err_code: 2,
//         message: '昵称已存在'
//       })
//     }

//     // 对密码进行 md5 重复加密
//     body.password = md5(md5(body.password))

//     // 创建用户，执行注册
//     await new User(body).save()

//     res.status(200).json({
//       err_code: 0,
//       message: 'OK'
//     })
//   } catch (err) {
//     res.status(500).json({
//       err_code: 500,
//       message: err.message
//     })
//   }
// })

module.exports = router;